<template>
  <div class="page-data-auth-container">
    <el-dialog title="页面数据授权"
               :visible.sync="dialogVisible"
               width="60%"
               :before-close="handleClose">
      <el-row :gutter="20">
        <el-form :model="requestParam"
                 ref="requestParam">
          <el-col :span="24"
                  class="page-auth-content">
            <el-col :span="8"
                    class="left-box">
              <p class="tag-p-style">系统功能</p>
              <div class="tree-content">
                <el-tree :data="treeData"
                         class="tree-style"
                         show-checkbox
                         :default-checked-keys='defaultCheckKeys'
                         default-expand-all
                         @check="onCheckBoxChange"
                         :check-strictly="true"
                         node-key="object_id"
                         :props="defaultProps">
                </el-tree>
              </div>
            </el-col>
            <el-col :span="16"
                    class="right-box">
              <p class="tag-p-style">权限配置</p>
              <div class="radio-content">
                <el-form-item label-width="0px">
                  <el-radio v-model="requestParam.view_obj"
                            label="1">仅允许查看</el-radio>
                </el-form-item>
              </div>
            </el-col>
          </el-col>
          <el-col :span="
                   24"
                  class="bottom-box">
            <el-button @click="onBack">返回</el-button>
            <el-button type="primary"
                       @click="onSure">确定</el-button>
          </el-col>
        </el-form>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { ProjectListApi } from "@/services/ProjectCenter";
export default {
  props: {
    objRow: {
      type: Object,
      default: () => {
        return {}
      }
    },
    pageDataAuthVisible: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  data () {
    return {
      project_id: '',
      recordOldObjeIds: [],//记录回显的obj_id的值
      defaultCheckKeys: [],//默认选中
      selectedObj: { checkedKeys: [] },
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'object_name'
      },
      dialogVisible: false,
      requestParam: {//参数
        del_object_ids: '',
        view_obj: '1',//默认为仅允许查看
        project_id: '',
        project_rela_id: '',
        object_ids: '',
      }
    }
  },
  methods: {
    onCheckBoxChange (checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys) {//复选框值改变时触发的事件
      this.selectedObj = checkedKeys;
    },
    getPageObjListByUser () {//项目权限-获取当前用户可查看的项目页面权限列表
      let store = this.$store.state.choosedProject
      let local = window.localStorage.getItem('choosedProject') || '{}'
      this.choosedProject = store.project_id ? store : JSON.parse(local)
      this.project_id = this.choosedProject.project_id
      return ProjectListApi.getPageObjListByUser({
        params: {
          project_id: this.project_id
        }
      }).then((res) => {
        if (res.data) {
          this.treeData = res.data;
          this.getChildren(this.treeData)
          if (this.treeData.length > 0) {
            this.treeData.map((item) => {
              if (item.is_dir == 1) {
                this.$set(item, 'disabled', true);
              }
            })
          }
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    getChildren (data) {
      data.forEach(ele => {
        if (ele.children) {
          this.getChildren(ele.children)
          ele.children.map(item => {
            if (item.is_not_select == '1') {
              this.$set(item, 'disabled', true)
            }
          })
        }
      });
    },
    onBack () {//返回
      this.recordOldObjeIds = [];
      this.selectedObj.checkedKeys = [];
      this.requestParam = this.$options.data().requestParam;
      this.defaultCheckKeys = [];
      this.dialogVisible = false;
      this.$emit('update:objRow', {});
      this.$emit('update:pageDataAuthVisible', false);
    },
    getCancelObjIds (objIds) {
      let objectIds = objIds == '' ? [] : objIds.split(',');
      let newArr = [];
      if (this.recordOldObjeIds.length > 0) {
        for (var i = 0; i < this.recordOldObjeIds.length; i++) {
          if (objectIds.includes(String(this.recordOldObjeIds[i])) == false) {
            newArr.push(this.recordOldObjeIds[i])
          }
        }
      };
      return newArr.length > 0 ? newArr.join(',') : '';
    },
    save (objectIds) {
      this.requestParam.del_object_ids = this.getCancelObjIds(objectIds);//原来选中，但是取消了的主键值
      this.requestParam.project_id = this.objRow.prp_project_id;
      this.requestParam.project_rela_id = this.objRow.prp_project_rela_id;
      this.requestParam.object_ids = objectIds;
      ProjectListApi.authProPageObj({
        data: this.requestParam
      }).then((res) => {
        if (res.code == 0) {
          this.onBack();//返回
          this.$message.success('操作成功')
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    getObjIds () {
      let checkedIds = this.selectedObj.checkedKeys;
      let objIds = checkedIds.length > 0 ? checkedIds.join(',') : '';
      return objIds;
    },
    onSure () {//确定
      let objectIds = this.getObjIds();//选中页面的主键值
      if (objectIds == '') {
        this.$message.warning('功能页面至少选中一个!')
      } else {
        this.save(objectIds)//保存
      }

    },
    handleClose (done) {//弹框关闭
      this.onBack();
      done();
    },
    getPageDataAuth () {//获取页面数据授权
      return ProjectListApi.getPageDataAuth({
        params: {
          project_id: this.objRow.prp_project_id,
          project_rela_id: this.objRow.prp_project_rela_id
        }
      }).then((res) => {
        if (res.data) {
          let list = res.data.list;
          if (list.length > 0) {//回显
            list.map((item) => {
              this.selectedObj.checkedKeys.push(item.page_object_id);//功能页面的主键值
            })
          };
          this.defaultCheckKeys = this.selectedObj.checkedKeys;
          this.recordOldObjeIds = this.defaultCheckKeys;//记录上一次已保存的obj_id值
        }
      }).catch((error) => {
        console.log(error)
      })

    }
  },
  watch: {//监听
    async pageDataAuthVisible (n, o) {
      if (n == true) {
        await this.getPageObjListByUser();
        await this.getPageDataAuth();//获取页面数据授权
        this.dialogVisible = true;
      }
    }
  },
  async created () {
    if (this.pageDataAuthVisible == true) {
      await this.getPageObjListByUser();
      await this.getPageDataAuth();//获取页面数据授权
      this.dialogVisible = true;
    }
  }
}
</script>

<style lang="scss" scoped>
.page-data-auth-container {
  .page-auth-content {
    display: flex;
    flex-direction: row;
    .tag-p-style {
      font-size: 16px;
      font-weight: 400px;
      font-family: "Arial Normal", "Arial", sans-serif;
      height: 56px;
      line-height: 56px;
      text-align: center;
      border-bottom: 1px solid #333;
      margin-bottom: 20px;
    }
    .left-box {
      padding: 0px !important;
      height: 400px;
      border: 1px solid #333;
      border-radius: 4px;
      .tree-content {
        overflow: scroll;
        padding: 0px 20px;
        height: 320px;
        overflow-y: auto;
      }
    }
    .right-box {
      padding: 0px !important;
      border-radius: 4px;
      margin-left: 20px;
      height: 400px;
      border: 1px solid #333;
      .radio-content {
        padding: 0px 20px;
        height: 341px;
        overflow-y: auto;
      }
    }
  }
  .bottom-box {
    margin-top: 24px;
    text-align: center;
  }
}
</style>